package cn.kgm.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {
    // Windows 发送消息
    // 1，打开cmd窗口，输入telnet 127.0.0.1 6666
    // 2，按下 ctrl + 】 进入输入页面
    // 3, 输入数据
    public static void main(String[] args) throws IOException {
        ExecutorService bioThreadPool = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("sercer is started");
        for (;;){
            // 阻塞线程等待连接
            final Socket accept = serverSocket.accept();
            System.out.println("linked one client socket");
            bioThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    // 重写run
                    try{
                        System.out.println("thread=>" + Thread.currentThread().getId());
                        System.out.println("threadName=>" + Thread.currentThread().getName());
                        handler(accept);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    public static void handler(Socket socket) throws IOException{
        byte[] bytes = new byte[1024];
        try{
            // 阻塞读取等待数据发送
            final InputStream inputStream = socket.getInputStream();
            int read = 0;
            for (;;){
                read += inputStream.read(bytes);
                if (read!=-1){
                    // 不等于-1 还可以继续读，没数据的时候会返回-1
                    System.out.println(new java.lang.String(bytes,0,read));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            socket.close();
        }
    }
}
